package com.example.basic_ui_demo.view.teams

import android.os.Build
import android.util.Log
import androidx.annotation.RequiresApi
import androidx.annotation.RequiresExtension
import androidx.compose.foundation.ExperimentalFoundationApi
import androidx.compose.foundation.Image
import androidx.compose.foundation.clickable
import androidx.compose.foundation.gestures.Orientation
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.automirrored.filled.ArrowBack
import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.material3.Icon
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.unit.dp
import androidx.navigation.NavController
import com.example.basic_ui_demo.R
import com.example.basic_ui_demo.companion.ApiViewModel
import com.example.basic_ui_demo.companion.data.RetrofitInstance
import com.example.basic_ui_demo.view.MyScrollableAppBar
import com.example.basic_ui_demo.view.TAG
import com.example.basic_ui_demo.view_model.TeamsViewModel
import com.example.basic_ui_demo.view_model.TeamsViewModel.Companion.tabs
import com.lt.compose_views.compose_pager.ComposePager

@OptIn(ExperimentalFoundationApi::class)
@RequiresExtension(extension = Build.VERSION_CODES.S, version = 7)
@RequiresApi(Build.VERSION_CODES.O)
@Composable
fun TeamDetailScreen(navController: NavController, viewModel: TeamsViewModel, teamId: Int) {

    val curIndex by remember { viewModel.composePagerState.getCurrSelectIndexState() }
    //pager当前index(对应tabs)

    var isLoading by remember { viewModel.isLoading }
    //加载指示器

    var isError by remember { viewModel.isError }
    //加载失败指示器

    val curSeason by remember { viewModel.season }
    //当前选择的赛季

    var team by remember { mutableStateOf(viewModel.getTeam(curSeason, teamId)) }
    //当前加载的team,首先从TeamsViewModel中寻找,确认是否来自TeamsScreen,否则调用api查找team

    LaunchedEffect(Unit) {
        isLoading = true
        val api = RetrofitInstance.api
        if (team == null) {
            Log.d(TAG, "team no cache, get new cache")
            team = ApiViewModel.callApi {
                api.getTeamById(teamId, curSeason)
            }
        }
        isError = team?.let {
            viewModel.addTeam(curSeason, teamId, it)
            //add new team cache
            false
        } ?: true
        isLoading = false
    }

    //可伸展的topBar
    MyScrollableAppBar(
        title = team?.shortName.toString(),
        crest = team?.crest.toString(),
        maxScrollPosition = 120.dp,
        modifier = Modifier.fillMaxWidth(),
        background = painterResource(id = R.drawable.playground),
        navigationIcon = {
            Icon(
                imageVector = Icons.AutoMirrored.Filled.ArrowBack,
                contentDescription = "ArrowBack",
                tint = Color.White,
                modifier = Modifier.clickable {
                    navController.popBackStack()
                }
            )
        }
    ) {
        Column {
            ComposePager(
                pageCount = tabs.size,
                modifier = Modifier
                    .fillMaxSize()
                    .align(Alignment.CenterHorizontally),
                composePagerState = viewModel.composePagerState,
                orientation = Orientation.Horizontal,
                pageCache = 1,
            ) {
                if (isError)
                    Box(contentAlignment = Alignment.Center) {
                        Box(modifier = Modifier.fillMaxSize(0.5f)) {
                            Image(
                                painter = painterResource(id = R.drawable.error_icon),
                                contentDescription = ""
                            )
                        }
                    }
                else if (isLoading)
                    Box(Modifier.fillMaxSize(), contentAlignment = Alignment.Center) {
                        CircularProgressIndicator(Modifier.fillMaxSize(0.3f))
                    }
                else {
                    when (tabs[curIndex]) {
                        "基本信息" -> {
                            InformationCompose(viewModel, team!!)
                        }

                        "阵容" -> {
                            SquadCompose(viewModel, team, teamId)
                        }

                        "赛程" -> {
                            TeamMatchesCompose(navController, viewModel, teamId)
                        }
                    }
                }
            }
        }
    }
}
